﻿using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间.MaterialDetail;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin.SkinControl;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;
using ERP_SaaS_WinForm.登录.Common;

namespace ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlanDetail
{
    public partial class ProductDetailMain : Form
    {
        private PlanData currentPlanData;
        private List<Product> productList = new List<Product>();
        private List<MaterialDetailData> materialList = new List<MaterialDetailData>();
        private CCWin.SkinControl.SkinDataGridView dgvMaterial;
        
        public ProductDetailMain(PlanData planData)
        {
            InitializeComponent();
            currentPlanData = planData;
            
            LoadPlanData();
        }
        private void LoadPlanData()
        {
            try
            {
                // 设置窗体标题
                this.Text = $"生产计划详情 - {currentPlanData.planName}";
                
                // 填充四个输入框的数据
                if (!string.IsNullOrEmpty(currentPlanData.planName))
                {
                    txtDetailName.Text = currentPlanData.planName;
                }
                
                if (!string.IsNullOrEmpty(currentPlanData.planCode))
                {
                    txtDetailCode.Text = currentPlanData.planCode;
                }
                
                if (!string.IsNullOrEmpty(currentPlanData.createName))
                {
                    txtCreateName.Text = currentPlanData.createName;
                }
                
                if (currentPlanData.createDate.HasValue)
                {
                    dtpCreateTime.text = currentPlanData.createDate.Value.ToString("yyyy-MM-dd");
                }
                else
                {
                    dtpCreateTime.text = DateTime.Now.ToString("yyyy-MM-dd");
                }
                
                // 设置窗体基本属性
                this.StartPosition = FormStartPosition.CenterParent;
                this.FormBorderStyle = FormBorderStyle.Sizable;
                this.MaximizeBox = true;
                this.MinimizeBox = true;
                
                // 设置窗体大小
                this.Size = new Size(1200, 800);
                
                // 设置TabPage的文本
                tabBasic.Text = "基础信息";
                tabProduct.Text = "生产产品";
                
                // 设置默认选中基础信息页面
                tabDetail.SelectedIndex = 0;
                
                // 可以在这里添加更多详细信息到TabPage中
                LoadBasicInfo();
                
                // 延迟初始化页面，确保控件已完全加载
                this.Load += (sender, e) => {
                    try
                    {
                        // 初始化生产产品页面
                        InitializeProductPage();
                        
                        // 加载产品数据
                        LoadProductData();
                        
                        // 初始化物料明细页面
                        InitializeMaterialPage();
                        
                        // 加载物料明细数据
                        LoadMaterialData();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"初始化页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                };
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载计划数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 加载基础信息到TabPage
        /// </summary>
        private void LoadBasicInfo()
        {
            try
            {
                Console.WriteLine("=== 开始加载基础信息 ===");
                Console.WriteLine($"currentPlanData: {currentPlanData?.planName ?? "null"}");
                
                // 检查currentPlanData是否为空
                if (currentPlanData == null)
                {
                    MessageBox.Show("计划数据为空，无法加载基础信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 计划编号
                if (!string.IsNullOrEmpty(currentPlanData.planCode))
                {
                    txtPlanCode.Text = currentPlanData.planCode;
                    Console.WriteLine($"设置计划编号: {currentPlanData.planCode}");
                }
                else
                {
                    Console.WriteLine("计划编号为空");
                }
                
                // 计划名称
                if (!string.IsNullOrEmpty(currentPlanData.planName))
                {
                    skinTextBox1.Text = currentPlanData.planName;
                    Console.WriteLine($"设置计划名称: {currentPlanData.planName}");
                }
                else
                {
                    Console.WriteLine("计划名称为空");
                }
                
                // 来源类型
                if (currentPlanData.resource > 0)
                {
                    string resourceText = GetResourceText(currentPlanData.resource);
                    txtResource.Text = resourceText;
                    Console.WriteLine($"设置来源类型: {resourceText}");
                }
                else
                {
                    Console.WriteLine("来源类型为空或为0");
                }
                
                // 订单编号
                if (currentPlanData.salesOrderId.HasValue && currentPlanData.salesOrderId.Value > 0)
                {
                    txtOrderCode.Text = currentPlanData.salesOrderId.Value.ToString();
                    Console.WriteLine($"设置订单编号: {currentPlanData.salesOrderId.Value}");
                }
                else
                {
                    Console.WriteLine("订单编号为空或为0");
                }
                
                // 成品名称
                if (!string.IsNullOrEmpty(currentPlanData.productName))
                {
                    txtProductName.Text = currentPlanData.productName;
                    Console.WriteLine($"设置成品名称: {currentPlanData.productName}");
                }
                else
                {
                    Console.WriteLine("成品名称为空");
                }
                
                // 成品编号
                if (!string.IsNullOrEmpty(currentPlanData.productCode))
                {
                    txtProductCode.Text = currentPlanData.productCode;
                    Console.WriteLine($"设置成品编号: {currentPlanData.productCode}");
                }
                else
                {
                    Console.WriteLine("成品编号为空");
                }
                
                // 规格型号
                if (!string.IsNullOrEmpty(currentPlanData.specification))
                {
                    txtSpecification.Text = currentPlanData.specification;
                    Console.WriteLine($"设置规格型号: {currentPlanData.specification}");
                }
                else
                {
                    Console.WriteLine("规格型号为空");
                }
                
                // 计划数量
                if (currentPlanData.planNum > 0)
                {
                    txtplannum.Text = currentPlanData.planNum.ToString();
                    Console.WriteLine($"设置计划数量: {currentPlanData.planNum}");
                }
                else
                {
                    Console.WriteLine("计划数量为空或为0");
                }
                
                // 单位
                if (!string.IsNullOrEmpty(currentPlanData.unitName))
                {
                    txtunit.Text = currentPlanData.unitName;
                    Console.WriteLine($"设置单位: {currentPlanData.unitName}");
                }
                else
                {
                    Console.WriteLine("单位为空");
                }
                
                // 计划开工时间
                if (currentPlanData.planStart.HasValue)
                {
                    dtpstarttime.text = currentPlanData.planStart.Value.ToString("yyyy-MM-dd");
                    Console.WriteLine($"设置计划开工时间: {currentPlanData.planStart.Value:yyyy-MM-dd}");
                }
                else
                {
                    Console.WriteLine("计划开工时间为空");
                }
                
                // 计划完工时间
                if (currentPlanData.planEnd.HasValue)
                {
                    dtpcompletetime.text = currentPlanData.planEnd.Value.ToString("yyyy-MM-dd");
                    Console.WriteLine($"设置计划完工时间: {currentPlanData.planEnd.Value:yyyy-MM-dd}");
                }
                else
                {
                    Console.WriteLine("计划完工时间为空");
                }
                
                // 需求日期
                if (currentPlanData.requireDate.HasValue)
                {
                    dtprequiretime.text = currentPlanData.requireDate.Value.ToString("yyyy-MM-dd");
                    Console.WriteLine($"设置需求日期: {currentPlanData.requireDate.Value:yyyy-MM-dd}");
                }
                else
                {
                    Console.WriteLine("需求日期为空");
                }
                
                Console.WriteLine("=== 基础信息加载完成 ===");
             
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载基础信息时出错: {ex.Message}");
                MessageBox.Show($"加载基础信息时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 获取来源类型的中文描述
        /// </summary>
        /// <param name="resourceValue">来源类型值</param>
        /// <returns>中文描述</returns>
        private string GetResourceText(int resourceValue)
        {
            switch (resourceValue)
            {
                case 1:
                    return "销售订单";
                case 2:
                    return "库存备货";
                case 3:
                    return "其他";
                default:
                    return "未知";
            }
        }
        

        
        /// <summary>
        /// 初始化生产产品页面
        /// </summary>
        private void InitializeProductPage()
        {
           
               
                // 设置生产产品 DataGridView的基本属性
                dgvProducts.AutoGenerateColumns = false;
                
                // 设置CSkin DataGridView样式
                dgvProducts.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(240, 248, 255);
                dgvProducts.DefaultCellStyle.SelectionBackColor = Color.FromArgb(59, 188, 240);
                dgvProducts.DefaultCellStyle.SelectionForeColor = Color.White;
                dgvProducts.RowHeadersVisible = false;
                dgvProducts.AllowUserToAddRows = false;
                dgvProducts.AllowUserToDeleteRows = false;
                dgvProducts.ReadOnly = true;
                dgvProducts.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvProducts.MultiSelect = false;
                
                // 设置CSkin特有的样式
                dgvProducts.BackColor = Color.White;
                dgvProducts.BorderStyle = BorderStyle.None;
                dgvProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
                dgvProducts.RowTemplate.Height = 30;
                
                Console.WriteLine("生产产品页面初始化完成");
           
        }
        
        /// <summary>
        /// 初始化物料明细页面
        /// </summary>
        private void InitializeMaterialPage()
        {
            try
            {
                // 创建物料明细TabPage
                var materialTabPage = new CCWin.SkinControl.SkinTabPage();
                materialTabPage.Text = "物料明细";
                materialTabPage.Name = "materialTabPage";
                
                // 创建物料明细DataGridView控件
                var dgvMaterial = new CCWin.SkinControl.SkinDataGridView();
                dgvMaterial.Name = "dgvMaterial";
                dgvMaterial.Dock = DockStyle.Fill;
                dgvMaterial.Location = new Point(0, 0);
                dgvMaterial.Size = new Size(materialTabPage.Width, materialTabPage.Height);
                
                // 设置物料明细 DataGridView的基本属性
                dgvMaterial.AutoGenerateColumns = false;
                dgvMaterial.Columns.Clear();
                
                // 添加物料明细列定义
                // 物料编号列
                DataGridViewTextBoxColumn colMaterialCode = new DataGridViewTextBoxColumn();
                colMaterialCode.HeaderText = "物料编号";
                colMaterialCode.DataPropertyName = "materialCode";
                colMaterialCode.Width = 120;
                colMaterialCode.ReadOnly = true;
                dgvMaterial.Columns.Add(colMaterialCode);
                
                // 物料名称列
                DataGridViewTextBoxColumn colMaterialName = new DataGridViewTextBoxColumn();
                colMaterialName.HeaderText = "物料名称";
                colMaterialName.DataPropertyName = "materialName";
                colMaterialName.Width = 150;
                colMaterialName.ReadOnly = true;
                dgvMaterial.Columns.Add(colMaterialName);
                
                // 单位列
                DataGridViewTextBoxColumn colUnit = new DataGridViewTextBoxColumn();
                colUnit.HeaderText = "单位";
                colUnit.DataPropertyName = "unit";
                colUnit.Width = 80;
                colUnit.ReadOnly = true;
                dgvMaterial.Columns.Add(colUnit);
                
                // 规格型号列
                DataGridViewTextBoxColumn colSpecification = new DataGridViewTextBoxColumn();
                colSpecification.HeaderText = "规格型号";
                colSpecification.DataPropertyName = "specification";
                colSpecification.Width = 120;
                colSpecification.ReadOnly = true;
                dgvMaterial.Columns.Add(colSpecification);
                
                // 物料属性列
                DataGridViewCheckBoxColumn colAttribute = new DataGridViewCheckBoxColumn();
                colAttribute.HeaderText = "物料属性";
                colAttribute.DataPropertyName = "attribute";
                colAttribute.Width = 100;
                colAttribute.ReadOnly = true;
                dgvMaterial.Columns.Add(colAttribute);
                
                // 设置CSkin DataGridView样式
                dgvMaterial.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(240, 248, 255);
                dgvMaterial.DefaultCellStyle.SelectionBackColor = Color.FromArgb(59, 188, 240);
                dgvMaterial.DefaultCellStyle.SelectionForeColor = Color.White;
                dgvMaterial.RowHeadersVisible = false;
                dgvMaterial.AllowUserToAddRows = false;
                dgvMaterial.AllowUserToDeleteRows = false;
                dgvMaterial.ReadOnly = true;
                dgvMaterial.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvMaterial.MultiSelect = false;
                
                // 设置CSkin特有的样式
                dgvMaterial.BackColor = Color.White;
                dgvMaterial.BorderStyle = BorderStyle.None;
                dgvMaterial.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
                dgvMaterial.RowTemplate.Height = 30;
                
                // 将DataGridView添加到物料明细页面
                materialTabPage.Controls.Add(dgvMaterial);
                
                // 将物料明细页面添加到TabControl
                tabDetail.TabPages.Add(materialTabPage);
                
                // 保存控件引用
                this.dgvMaterial = dgvMaterial;
                
                Console.WriteLine("物料明细页面初始化完成，已添加5列");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化物料明细页面时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        
     
      
        

        
        
     
      
        
        /// <summary>
        /// 加载产品数据
        /// </summary>
        private async void LoadProductData()
        {
            try
            {
                // 检查JWT授权状态
                if (!JwtAuthHelper.CheckLoginStatus())
                {
                    return;
                }
                
                // 显示加载状态
                dgvProducts.DataSource = null;
                
                // 调用产品 API
                Console.WriteLine("正在调用产品API...");
                var apiResponse = await ApiRequestHelper.GetAsync<ApiResponse>("api/Plan/GetProduct");
                
                if (apiResponse.Success && apiResponse.Data?.code == 200 && apiResponse.Data.data != null)
                {
                    Console.WriteLine($"产品API调用成功，数据条数: {apiResponse.Data.data.Count}");
                    
                    // 转换数据 - 与SelectProduct.cs保持一致
                    productList = apiResponse.Data.data.Select(p => new Product
                    {
                        ProductId = p.productId,
                        ProductCode = p.productCode,
                        ProductName = p.productName,
                        Specification = p.specification,
                        UnitName = p.unitName
                    }).ToList();
                    
                    // 设置产品数据到DataGridView
                    dgvProducts.DataSource = productList;
                    
                    // 调整列宽
                    dgvProducts.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                    
                    Console.WriteLine($"成功加载 {productList.Count} 个产品数据");
                }
                else
                {
                    string errorMsg = apiResponse.Success ? 
                        $"产品数据加载失败: {apiResponse.Data?.msg ?? "未知错误"}" : 
                        $"请求失败: {apiResponse.Message}";
                    Console.WriteLine($"产品API调用失败: {errorMsg}");
                    ApiRequestHelper.ShowError(errorMsg);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载产品数据时出错: {ex.Message}");
                MessageBox.Show($"加载产品数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 加载物料明细数据
        /// </summary>
        private async void LoadMaterialData()
        {
            try
            {
                Console.WriteLine("=== 开始加载物料明细数据 ===");
                
                // 检查dgvMaterial控件是否存在
                if (dgvMaterial == null)
                {
                    MessageBox.Show("物料明细 DataGridView控件未找到", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 检查JWT授权状态
                if (!JwtAuthHelper.CheckLoginStatus())
                {
                    return;
                }
                
                // 显示加载状态
                dgvMaterial.DataSource = null;
                
                // 使用硬编码的物料明细API（因为需要特定的参数和不同的服务器地址）
                Console.WriteLine("正在调用物料明细API...");
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 添加JWT授权头
                    if (TokenDto.IsLoggedIn)
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenDto.JwtToken);
                        Console.WriteLine("已添加JWT授权头");
                    }
                    
                    // 使用硬编码的API地址和参数
                    var response = await client.GetAsync("http://10.223.8.23:8008/api/Material/GetMaterialInfo?PickState=true");
                    
                    // 检查响应状态
                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        Console.WriteLine("物料明细API返回401未授权错误");
                        var result = MessageBox.Show("登录已过期，是否重新登录？", "登录过期", 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        
                        if (result == DialogResult.Yes)
                        {
                            // 清除当前token
                            TokenDto.Clear();
                            
                            // 打开登录窗体
                            var loginForm = new LoginForm();
                            loginForm.ShowDialog();
                            
                            // 如果重新登录成功，重新调用API
                            if (TokenDto.IsLoggedIn)
                            {
                                LoadMaterialData();
                                return;
                            }
                        }
                        return;
                    }
                    
                    response.EnsureSuccessStatusCode();
                    
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"物料明细API响应: {jsonResponse}");
                    
                    MaterialApiResponse apiResponse = JsonConvert.DeserializeObject<MaterialApiResponse>(jsonResponse);
                    
                    if (apiResponse?.code == 200 && apiResponse.data != null)
                    {
                        Console.WriteLine($"物料明细API调用成功，数据条数: {apiResponse.data.Count}");
                        
                        // 设置物料明细数据到DataGridView
                        materialList = apiResponse.data;
                        dgvMaterial.DataSource = materialList;
                        
                        // 调整列宽
                        dgvMaterial.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                        
                        Console.WriteLine($"成功加载 {materialList.Count} 个物料明细数据");
                        Console.WriteLine("=== 物料明细数据加载完成 ===");
                    }
                    else
                    {
                        string errorMsg = $"物料明细数据加载失败: {apiResponse?.message ?? "未知错误"}";
                        Console.WriteLine($"物料明细API调用失败: {errorMsg}");
                        MessageBox.Show(errorMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载物料明细数据时出错: {ex.Message}");
                MessageBox.Show($"加载物料明细数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvMaterial_Click(object sender, EventArgs e)
        {

        }
    }
}
